package com.example.imtoken.modules.user.recovery

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.example.imtoken.R
import com.example.imtoken.core.App
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.http.BaseObserver
import com.example.imtoken.core.logic.network.RetrofitUtils
import com.example.imtoken.core.logic.repository.WalletRepository
import com.example.imtoken.core.utils.Utils
import com.example.imtoken.core.utils.sp.SpHelps
import com.example.imtoken.entitys.http.CreateEntity
import com.example.imtoken.entitys.http.ResponseEntity
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.AccountSchema
import com.example.imtoken.room.schema.AppLoginSchema
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.launch
import java.lang.Exception

class RecoveryUserViewModel(private val repository: WalletRepository) : BaseViewModel() {

    val mnemonic = MutableLiveData<String>()
    val passWord1 = MutableLiveData<String>()
    val passWord2 = MutableLiveData<String>()
    val hint = MutableLiveData<String>()

    val isCreateSuccess = MutableLiveData(false)

    val isSubmit = MutableLiveData(false)

    var _mnemonic: String? = null
        set(value) {
            field = value
            inspectEditText()
        }
    var _passWord1: String? = null
        set(value) {
            field = value
            inspectEditText()
        }
    var _passWord2: String? = null
        set(value) {
            field = value
            inspectEditText()
        }
    var _hint: String? = null
        set(value) {
            field = value
            inspectEditText()
        }

    private fun inspectEditText() {
        isSubmit.value =
            _mnemonic?.length ?: 0 > 0 && _passWord1?.length ?: 0 > 0 && _passWord2?.length ?: 0 > 0
    }

    fun verifyParams(): Boolean {
        return when {
            Utils.verifyMnemonic(mnemonic.value) == null -> {
                mErrorResId.value = R.string.invalidMnemonicWords
                false
            }
            passWord1.value != passWord2.value -> {
                mErrorResId.value = R.string.createUserTips_pass
                false
            }
            else -> {
                true
            }
        }
    }

    fun createUser() {
        mDialog.value = true
        viewModelScope.launch {
            try {
                val createEntity = repository.createUser(
                    "eth",
                    passWord1.value,
                    "identity_name",
                    hint.value
                )
                repository.addAccountData(
                    createEntity,
                    passWord1.value,
                    "identity_name",
                    hint.value
                )
                repository.addAppLoginData(createEntity[0].coin?.address)
                App.createLiveData.value = createEntity[0]

                App.appCode?.let { code ->
                    val bindingWallet = repository.bindingWallet(
                        createEntity[0].coin?.address,
                        passWord1.value,
                        "eth",
                        code
                    )
                    bindingWallet?.let { LogUtils.json(it) }
                }
                mDialog.value = false
                isCreateSuccess.value = true
                SPUtils.getInstance(SpHelps.APP).put(SpHelps.APP_LOGIN, true)
            }catch (e:Exception){
                mDialog.value = false
                mErrorStr.value = e.message
            }
        }

//        RetrofitUtils.apiService?.walletCreate(
//            "eth",
//            passWord1.value,
//            "identity_name",
//            hint.value
//        )?.subscribeOn(Schedulers.io())
//            ?.unsubscribeOn(Schedulers.io())
//            ?.subscribe(object : BaseObserver<ResponseEntity<CreateEntity>>() {
//                override fun onSuccess(value: ResponseEntity<CreateEntity>) {
//                    mDialog.postValue(false)
//                    if (value.code == 0) {
//                        addAccountData(value.data)
//                        addAppLoginData(value.data?.get(0)?.coin?.address)
//                        App.createLiveData.postValue(value.data?.get(0))
//                        isCreateSuccess.postValue(true)
//                        SPUtils.getInstance(SpHelps.APP).put(SpHelps.APP_LOGIN, true)
//                    } else {
//                        mErrorStr.postValue(value.msg)
//                    }
//                }
//
//                override fun onFailed(e: Throwable) {
//                    mDialog.postValue(false)
//                    LogUtils.e(e.message)
//                }
//            })
    }

//    private fun addAccountData(createEntity: CreateEntity?) {
//        createEntity?.forEach {
//            val account = AccountSchema(
//                "identity_name",
//                _passWord1,
//                _hint,
//                it.token,
//                it.coin?.address,
//                it.coin?.coin,
//                it.coin?.mnemonic,
//                it.coin?.public_key,
//                it.coin?.coin,
//                1
//            )
//            if (AppDataBase.instance.getAccountDao().insertAccount(account) > 0) {
//                LogUtils.e("${it.coin} --->>> 钱包账号添加成功")
//            } else {
//                LogUtils.e("${it.coin} --->>> 钱包账号添加失败")
//            }
//        }
//    }
//
//    private fun addAppLoginData(address: String?) {
//        val appLogin = AppLoginSchema(address)
//        if (AppDataBase.instance.getAppLoginDao().insertAppLogin(appLogin) > 0) {
//            LogUtils.e("app登录标识添加成功")
//        } else {
//            LogUtils.e("app登录标识添加失败")
//        }
//    }

}